<template>
  <div class="updatePwd-container">
    <el-card style="width: 45%; text-align: center; margin-left: 28%; height:87vh;">
      <div style="text-align: left; margin: 0 0 0 0;">
        <span class="textShadow" style="font-size: 26px;color: black;font-weight: bold">修改密码</span>
      </div>
      <div>
        <span>若账户为首次注册，初始密码为:123456</span>
      </div>
      <el-form ref="formRef" :model="user" :rules="rules" label-width="80px"
               style="padding-right: 10px; margin-top: 50px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" placeholder="请输入用户名" disabled></el-input>
        </el-form-item>
        <el-form-item label="原始密码" prop="password">
          <el-input v-model="user.password" type="password" placeholder="原始密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="user.newPwd" show-password placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input v-model="user.confirmPwd" show-password placeholder="确认密码"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="success" @click="update">确认修改</el-button>
        <el-button type="primary" @click="reBack">返 回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error("请输入确认密码"))
      } else if (value !== this.user.newPwd) {
        callback(new Error("确认密码与新密码不一致"))
      } else {
        callback()
      }
    }
    return {
      user: JSON.parse(sessionStorage.getItem('user-key' || {})),
      confirmPassword: '',
      rules: {
        password: [{
          required: true,
          message: '请输入原始密码',
          trigger: 'blur'
        }],
        newPwd: [{
          required: true,
          message: '请输入新密码',
          trigger: 'blur'
        }],
        confirmPwd: [{
          required: true,
          validator: validateConfirmPassword,
          trigger: 'blur'
        }],
      }
    }
  },
  methods: {
    update() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.user.password = this.user.newPwd
          //保存当前的用户信息到数据库
          this.$request.put('/user/updatePwd', this.user).then(res => {
            if (res.code === 200) {
              //成功更新
              this.$message.success('修改成功')
              this.$router.push('/')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }, reBack() {
      this.$router.push('/space')
    }
  }
}
</script>

<style scoped>
div /deep/ .el-form-item__label {
  font-weight: bold;
  font-size: 12px;
}
</style>